package com.example.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.to.es.SkuEsModel;
import com.example.common.utils.R;
import com.example.gulimall.search.config.gulimallElasticSearchConfig;
import com.example.gulimall.search.constant.EsConstant;
import com.example.gulimall.search.feign.ProductFeignService;
import com.example.gulimall.search.service.MallSearchService;
import com.example.gulimall.search.vo.AttrResponseVo;
import com.example.gulimall.search.vo.BrandVo;
import com.example.gulimall.search.vo.SearchParam;
import com.example.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public Object search(SearchParam param) {

        SearchResult result = new SearchResult();

        SearchRequest searchRequest = buildSearchRequest(param);
        try{
            SearchResponse search = client.search(searchRequest, gulimallElasticSearchConfig.COMMON_OPTIONS);

            result = buildSearchResult(search,param);

        }catch (IOException e){
            e.printStackTrace();
        }

        return result;
    }

    private SearchRequest buildSearchRequest(SearchParam param) {

        // 构建DSL语句
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 1.bool
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1.1 must
        if(!StringUtils.isEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }

        // 1.2 bool filter
        if (param.getCatelog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatelog3Id()));
        }

        if (param.getBrandId()!=null && param.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }

        if (param.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()));
        }

        // 2.Range
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");

        if (!StringUtils.isEmpty(param.getSkuPrice())){
            String[] price = param.getSkuPrice().split("_");
            if(price.length == 1){
                if(param.getSkuPrice().startsWith("_"))
                    rangeQueryBuilder.lte(Integer.parseInt(price[0]));
                else
                    rangeQueryBuilder.gte(Integer.parseInt(price[0]));
            }else if(price.length == 2){
                if(!price[0].isEmpty())
                rangeQueryBuilder.gte(Integer.parseInt(price[0]));
                rangeQueryBuilder.lte(Integer.parseInt(price[1]));
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        // 1.2.5 nested
        List<String> attrs = param.getAttrs();
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if (attrs != null && attrs.size() > 0){
            for(String attr: attrs){
                String[] s = attr.split("_");
                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId",s[0]));

                String[] split = s[1].split(":");
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",split));
            }
        }
        NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs",queryBuilder, ScoreMode.None);
        boolQueryBuilder.filter(nestedQueryBuilder);
        // bool条件完成
        builder.query(boolQueryBuilder);


        // 2.sort
        if(!StringUtils.isEmpty(param.getSort())){
            String[] sortSplit = param.getSort().split("_");
            builder.sort(sortSplit[0],sortSplit[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC);
        }

        // 3.分页
        builder.from((param.getPageNum()-1)* EsConstant.PRODUCT_PAGESIZE);
        builder.size(EsConstant.PRODUCT_PAGESIZE);

        // 4.高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        // 5.聚合
        // 5.1 brand聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId");
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName");
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brandImgAgg").field("brandImg");

        brandAgg.subAggregation(brandNameAgg);
        brandAgg.subAggregation(brandImgAgg);
        builder.aggregation(brandAgg);

        // 5.2 catalog聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId");
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalogNameAgg").field("catalogName");
        catalogAgg.subAggregation(catalogNameAgg);
        builder.aggregation(catalogAgg);

        // 5.3 attrs聚合
        NestedAggregationBuilder nestedAggregationBuilder = new NestedAggregationBuilder("attrs","attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        nestedAggregationBuilder.subAggregation(attrIdAgg);
        builder.aggregation(nestedAggregationBuilder);

        String s = builder.toString();
        System.out.println("DSL:" + s);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},builder);
    }

    private SearchResult buildSearchResult(SearchResponse search, SearchParam param) {

        SearchResult result = new SearchResult();

        SearchHits hits = search.getHits();

        // 1.封装页码信息
        if (hits.getHits() != null && hits.getHits().length > 0){

            List<SkuEsModel> skuEsModels = new ArrayList<>();
            for (SearchHit hit : hits) {
                // 商品数据
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                //设置高亮数据
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.fragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                skuEsModels.add(skuEsModel);
            }
            result.setProducts(skuEsModels);
        }

        // 2.封装分页信息

        // 2.1 当前页码
        result.setPageNum(param.getPageNum());

        // 2.2 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 2.3 总页码
        Integer totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int) total / EsConstant.PRODUCT_PAGESIZE : (int) total % EsConstant.PRODUCT_PAGESIZE+1;
        result.setTotalPages(totalPages);


        // 3.封装
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        Aggregations aggregations = search.getAggregations();


        //parsedLongTerms用于接收terms聚合的结果，而且可以把key转换成long
        ParsedLongTerms brandAgg = aggregations.get("brandAgg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {

            // 3.1 获得品牌Id
            Long brandId = bucket.getKeyAsNumber().longValue();

            Aggregations subBrandAggs = bucket.getAggregations();

            // 3.2 得到品牌图片
            ParsedStringTerms brandImgAgg = subBrandAggs.get("brandImgAgg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();

            // 3.3 得到品牌名字
            Terms brandNameAgg = subBrandAggs.get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();

            SearchResult.BrandVo brandVo = new SearchResult.BrandVo(brandId, brandName, brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 涉及到的所有分类
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = aggregations.get("catalogAgg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {

            // 获取分类Id
            long catalogId = bucket.getKeyAsNumber().longValue();
            Aggregations subAggregations = bucket.getAggregations();

            // 获取分类名
            ParsedStringTerms catalogNameAgg = subAggregations.get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo(catalogId, catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 查询涉及到的所有属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrs = aggregations.get("attrs");
        ParsedLongTerms attrIdAgg = attrs.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {

            // 5.1 查询属性id
            Long attrId = bucket.getKeyAsNumber().longValue();
            Aggregations subAttrAgg = bucket.getAggregations();


            // 5.2 查询属性名
            ParsedStringTerms attrNameAgg = subAttrAgg.get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();

            // 5.3查询属性值
            ParsedStringTerms attrValueAgg = subAttrAgg.get("attrValueAgg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                String attrValue = attrValueAggBucket.getKeyAsString();
                attrValues.add(attrValue);
            }
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo(attrId, attrName, attrValues);
            attrVos.add(attrVo);
        }


        result.setAttrs(attrVos);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);




        // 构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0){
            List<SearchResult.NavVo> navVos = param.getAttrs().stream().map(attr -> {

                // 分析参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R info = productFeignService.info(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if(info.getCode() == 0){
                    AttrResponseVo infoData = info.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(infoData.getAttrName());
                }else
                    navVo.setNavName(s[0]);

                // 2.取消了面包屑
                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());

            if (param.getBrandId() != null && param.getBrandId().size() > 0) {
                List<SearchResult.NavVo> navs = result.getNavs();
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavName("品牌");
                //远程查询所有品牌
                R r = productFeignService.infos(param.getBrandId());
                if (r.getCode() == 0) {
                    List<BrandVo> brands = r.getData("brands", new TypeReference<List<BrandVo>>() {
                    });
                    StringBuffer buffer = new StringBuffer();
                    String replace = "";
                    for (BrandVo brandVo : brands){
                        buffer.append(brandVo.getBrandName()+";");
                        replace = replaceQueryString(param,brandVo.getBrandId()+"","brandId");
                    }
                    navVo.setNavValue(buffer.toString());
                    navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                }
                navs.add(navVo);
            }

            result.setNavs(navVos);
        }

        System.out.println(result.getAttrIds().toString());
        System.out.println(result.getAttrs().toString());
        return result;
    }

    //取消了面包屑之后,跳转的位置(将请求地址的url替换,置空)
    private String replaceQueryString(SearchParam paramVo, String value, String key) {
        String encode = null;
        try {
            //编码
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20");//对空格特殊处理(将空格变为%20)
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return paramVo.getUri().replace("&" + key + "=" + encode, "");
    }
}
